
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _ = db.command

export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *   "roleId": "122",
   *   "permissionIds": []
   * }
   */
  //1.校验数据
  if (nw.util.isNull(body.roleId)){
    return fail("角色id不能为空")
  }
  if (!nw.util.isArray(body.permissionIds)){
    return fail("数据不合法")
  }

  //2.构建保存数据
  let data = []
  for (let i = 0; i < body.permissionIds.length; i++) {
    let each = {
      roleId:body.roleId,
      permissionId:body.permissionIds[i],
      createTime:new Date(),
      updateTime:new Date(),
      deleted:0
    }
    data.push(each)
  }
  //3.删除已经有的数据
  await nw.db.update({
    dbName:"rolePermission",
    whereJson:{
      roleId:_.eq(body.roleId),
      deleted:0
    },
    dataJson:{deleted:1}
  })
  //4.保存数据结构即可
  let count = await db.collection("rolePermission").add(data,{multi:true})
  if (!count.ok){
    return fail("授权失败")
  }

  return ok("授权成功")

}
